#include "myStdio.h"
_FILE* fopen_(const char* fileName, const char* mode)
{
    int flag = 0;
    if(strcmp(mode, "r") == 0)
    {
        //以读的方式打开
        flag |= O_RDONLY;
    }
    else if(strcmp(mode, "w") == 0)
    {
        //以写的方式打开
        flag |= O_WRONLY | O_CREAT | O_TRUNC; 
    }
    else if(strcmp(mode, "a") == 0)
    {
        //以追加的方式打开
        flag |= O_WRONLY | O_CREAT | O_APPEND; 
    }
    else
    {
        //其他方式打开
    }
    int fd = 0;
    if(flag & O_RDONLY) 
        fd = open(fileName, flag);
    else 
        fd = open(fileName, flag, 0666);
    //打开文件失败
    if(fd == -1)
    {
        const char* err = strerror(errno);
        write(2, err, strlen(err));
        return NULL;
    }
    _FILE* pf = (_FILE*)malloc(sizeof(_FILE));
    pf->_fileno = fd;
    memset(pf->_buffer, 0, SIZE);
    pf->_size = 0;
    pf->_flag = SYNC_LINE;
    pf->_capacity = SIZE;
    return pf;
}
void fwrite_(const char* str, int num, _FILE* stream)
{
    memcpy(stream->_buffer + stream->_size, str, num);
    stream->_size += num;//不考虑缓冲区满的情况

    //判断刷新策略
    if(stream->_flag & SYNC_NOW)
    {
        write(stream->_fileno, stream->_buffer, stream->_size);
        stream->_size = 0;
    }
    else if(stream->_flag & SYNC_LINE) 
    {
        if(stream->_buffer[stream->_size - 1] == '\n')
        {
            write(stream->_fileno, stream->_buffer, stream->_size);
            stream->_size = 0;
        }
    }
    else if(stream->_flag & SYNC_FULL)
    {
        //暂时不考虑溢出的情况
        if(stream->_size == stream->_capacity)
        {
            write(stream->_fileno, stream->_buffer, stream->_size);
            stream->_size = 0;
        }
    }

}
void fflush_(_FILE* stream)
{
    write(stream->_fileno, stream->_buffer, stream->_size);
    //强制操作系统进行外设刷新
    fsync(stream->_fileno);
    stream->_size = 0;
}
void fclose_(_FILE* stream)
{
    fflush_(stream);
    close(stream->_fileno);
}
